﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Telerik.Windows.Controls;
using System.ComponentModel;
using System.Data;
using NHibernate;
using TChart=Telerik.Windows.Controls.Charting;
using Telerik.Windows.Controls.Charting;
using BrokerBase.Lib.Person;
using BrokerBase.Lib.Tool;
using BrokerBase.Lib.Policy;
using System.Threading;
using Broker.View.PersonView;
using Broker.View.PolicyView;

namespace Broker
{
    /// <summary>
    /// Interaction logic for HomePage.xaml
    /// </summary>
    public partial class HomePage
    {
        private BackgroundWorker worker;

        private const int Sale_Period = 6;

        public HomePage()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(HomePage_Loaded);
        }

        void HomePage_Loaded(object sender, RoutedEventArgs e)
        {
            buyRoot.IsBusy = true;
            worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerCompleted+=new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            worker.RunWorkerAsync();
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            LoadData();
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            buyRoot.IsBusy = false;
        }

        private void LoadData()
        {
            //Thread.Sleep(5000);
            LoadSales();
            //LoadProductInfo();
            LoadRemindBirthday();
            LoadRemindPayDate();
        }

        private void LoadSales()
        {
            using (ISession sess = AppGlobal.HbmSessionFactory.OpenSession())
            {
                DateTime dtEnd = DateTime.Now;
                DateTime dtBegin = dtEnd.AddMonths(Sale_Period * -1);

                int end = dtEnd.Year * 100 + dtEnd.Month;

                int begin = dtBegin.Year * 100 + dtBegin.Month;

                string sql = string.Format(@"select r.YearPeriod,ifnull(sp.F2,0),ifnull(sp.F3,0),ifnull(sp.F4,0) from Base_PeriodRange as r left join (select s.PeriodRange, count(s.Id) as F2,sum(p.Fee) as F3 ,sum(p.TotalFee)as F4 from Scheme as s  
                                    inner join Scheme_PolicyLight as p on s.id=p.OwnerId where s.checkTime is not null group by s.PeriodRange ) as sp on r.[YearPeriod]=sp.PeriodRange where   r.YearPeriod>{0} and r.YearPeriod<={1}", begin, end);

                ISQLQuery q = sess.CreateSQLQuery(sql);

                IList<object> ls = q.List<object>();

                IList<IList<SaleCollectModel>> values = new List<IList<SaleCollectModel>>();

                IList<SaleCollectModel> totalFees = new List<SaleCollectModel>();

                //values.Add(bills);
                //values.Add(fees);
                values.Add(totalFees);

                foreach (object[] o in ls)
                {

                    SaleCollectModel totalFee = new SaleCollectModel(Convert.ToInt64(o[0]), Convert.ToDouble(o[2]));
                    totalFees.Add(totalFee);

                }

                this.Dispatcher.Invoke(new Action(()=>
                    {
                        #region 设置 chart 和 数据 的绑定关系，因为在xaml中设置会出现问题（暂时不明白），所以采用代码方式
                        chartSale.SeriesMappings.Clear();
                        chartSale.ItemsSource = null;
                        chartSale.DefaultView.ChartArea.EnableAnimations = true;
                        //chartSale.DefaultView.ChartLegend.Header = "最近6个月保费总额";

                        SeriesMapping mapping = new SeriesMapping();


                        mapping.LegendLabel = "保费";

                        //mapping.LegendLabel = "";
                        mapping.CollectionIndex = 0;
                        //SplineSeriesDefinition def = new SplineSeriesDefinition();

                        BarSeriesDefinition bar = new BarSeriesDefinition();
                        //bar.LegendDisplayMode = LegendDisplayMode.SeriesLabel;
                        //bar.ShowItemLabels = false;
                        
                        bar.ItemLabelFormat = "0.00";
                        bar.ShowItemLabels = true;

                        mapping.SeriesDefinition = bar;
                        mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
                        mapping.ItemMappings.Add(new ItemMapping("YP", DataPointMember.XCategory));
                        chartSale.SeriesMappings.Add(mapping);

                        chartSale.ItemsSource = values;

                        #endregion
                    }));
            }
        }

        public void LoadProductInfo()
        {
            using (ISession sess = AppGlobal.HbmSessionFactory.OpenSession())
            {
                try
                {
                    object[] counts = sess.CreateSQLQuery(@"select count(*)as cmpcount,(select count(*) from product where producttype=1),
                        (select count(*) from product where producttype=2) from company").UniqueResult<object[]>();

                    int basicCount = Convert.ToInt32(counts[1]);
                    int extraCount = Convert.ToInt32(counts[2]);

                    int totalCount = basicCount + extraCount;

                    //this.Dispatcher.Invoke(new Action(() =>
                    //    {
                    //        runCompany.Text = counts[0].ToString();

                    //        runProduct.Text = totalCount.ToString();

                    //        runMain.Text = basicCount.ToString();

                    //        runExt.Text = extraCount.ToString();
                    //    }));


                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void LoadRemindBirthday()
        {
            using (ISession sess = AppGlobal.HbmSessionFactory.OpenSession())
            {
                IList<IPerson> cs = PersonUtil.LoadBirthdayRemind(DateTime.Now, AppGlobal.ClientCfg.BeforeBirthday, sess);

                this.Dispatcher.Invoke(new Action(() =>
                    {
                        gvBirthdayRemind.ItemsSource = cs;
                    }));
                
            }
        }

        private void LoadRemindPayDate()
        {
            using(ISession sess=AppGlobal.HbmSessionFactory.OpenSession())
            {
                IList<IPlanPayPeriod> pps = PolicyUtil.LoadRemindPayDate(DateTime.Now, AppGlobal.ClientCfg.BeforePayment, sess);

                IList<RemindPayRecord> rps = new List<RemindPayRecord>();

                foreach (IPlanPayPeriod pp in pps)
                {
                    RemindPayRecord rp = new RemindPayRecord();
                    rp.Holder = pp.Scheme.Holder.Name;
                    rp.Name = pp.Scheme.Insurant.Name;
                    rp.Amt = pp.Fee;
                    rp.PayDate = pp.PayTime;
                    rp.Scheme = pp.Scheme;

                    rps.Add(rp);
                }
                this.Dispatcher.Invoke(new Action(() =>
                    {
                        gvPayment.ItemsSource = rps;
                    }));
            }
        }

        private void SetChart()
        {
            #region  设置chart属性,因为在xaml中设置会出现问题（暂时不明白），所以采用代码方式
            chartSale.DefaultView.ChartLegend.Background = new SolidColorBrush(Colors.Transparent);
            chartSale.DefaultView.ChartLegend.BorderThickness = new Thickness(0);
            chartSale.DefaultView.ChartLegend.Header = "";
            //chartSale.DefaultView.ChartArea.AxisX.DefaultLabelFormat = "#VAL{yy年M月}";
            chartSale.DefaultView.ChartArea.AxisX.Step = 1;
            chartSale.DefaultView.ChartArea.AxisY.ExtendDirection = AxisExtendDirection.Up;
            chartSale.DefaultView.ChartArea.AxisY.MinorTicksVisibility = Visibility.Collapsed;
            chartSale.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Collapsed;
            chartSale.DefaultView.ChartArea.AxisY.MajorTicksVisibility = Visibility.Collapsed;
            chartSale.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            chartSale.DefaultView.ChartArea.AxisY.PlotAreaAxisVisibility = Visibility.Collapsed;
            #endregion
        }

        private void gvBirthdayRemind_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Person p = gvBirthdayRemind.SelectedItem as Person;

            if (p != null)
            {
                ISession sess =AppGlobal.HbmSessionFactory.GetCurrentSession();
                Person p2 = sess.CreateQuery("from Person as p where p.Id=" + p.Id).UniqueResult<Person>();

                PersonForm frm = new PersonForm(p2);

                frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frm.Owner = AppGlobal.MainWin;
                frm.ShowDialog();
            }
        }

        private void gvPayment_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            RemindPayRecord rpp = gvPayment.SelectedItem as RemindPayRecord;

            if (rpp != null)
            {
                ISession sess=AppGlobal.HbmSessionFactory.GetCurrentSession();
                Scheme scheme = sess.CreateQuery("from Scheme as s where s.Id=" + rpp.Scheme.Id).UniqueResult<Scheme>();

                Scheme2Form frm = new Scheme2Form(scheme, SchemeType.Normal);

                frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frm.Owner = AppGlobal.MainWin;
                frm.ShowDialog();
            }
        }
    }


    public class SaleCollectModel
    {
        public SaleCollectModel(long yp, double value)
        {
            YP = yp;
            Value = value;
        }

        public long YP { get; set; }

        public double Value { get; set; }
    }

    class RemindPayRecord
    {
        public string Holder { get; set; }

        public string Name { get; set; }

        public double Amt { get; set; }

        public DateTime PayDate { get; set; }

        public IScheme Scheme { get; set; }

    }

}
